let currentContentId = null;

document.addEventListener('DOMContentLoaded', function() {
    
    // 加载最近内容
    document.getElementById('loadRecentButton').addEventListener('click', loadRecentContent);

});

// 在模态框中显示内容
function showContentInModal(contentId) {
    window.currentContentId = contentId;
    // 显示加载中状态
    document.getElementById('contentViewContainer').innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mb-0">正在加载内容，请稍候...</p>
        </div>
    `;
    
    // 显示模态框
    const contentModal = new bootstrap.Modal(document.getElementById('contentViewModal'));
    contentModal.show();
    
    // 获取内容数据
    fetch(`/api/content/${contentId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('内容获取失败');
            }
            return response.json();
        })
        .then(data => {
            displayContentInModal(data);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('contentViewContainer').innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    加载内容失败: ${error.message || '未知错误'}
                </div>
            `;
            
            // 如果API不存在，尝试从页面已加载的内容中获取
            tryGetContentFromPage(contentId);
        });
}

// 尝试从页面已加载的内容中获取
function tryGetContentFromPage(contentId) {
    // 查找目标内容元素
    const contentElement = document.getElementById(`content-${contentId}`);
    if (contentElement) {
        // 克隆内容元素并显示在模态框中
        const clonedContent = contentElement.cloneNode(true);
        clonedContent.classList.add('highlight-content');
        document.getElementById('contentViewContainer').innerHTML = '';
        document.getElementById('contentViewContainer').appendChild(clonedContent);
    } else {
        // 如果页面中没有找到，尝试加载所有内容
        loadAllContent().then(() => {
            const reloadedContent = document.getElementById(`content-${contentId}`);
            if (reloadedContent) {
                const clonedContent = reloadedContent.cloneNode(true);
                clonedContent.classList.add('highlight-content');
                document.getElementById('contentViewContainer').innerHTML = '';
                document.getElementById('contentViewContainer').appendChild(clonedContent);
            } else {
                document.getElementById('contentViewContainer').innerHTML = `
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        无法找到指定内容
                    </div>
                `;
            }
        });
    }
}

// 在模态框中显示内容
function displayContentInModal(data) {

    // 批注功能已经通过模板直接加载，无需动态加载
    const container = document.getElementById('contentViewContainer');
    
    if (!data || data.error) {
        container.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-exclamation-triangle me-2"></i>
                ${data.error || '获取内容失败'}
            </div>
        `;
        return;
    }
    
    // 设置模态框标题为作者和发布时间信息
    document.getElementById('contentViewModalLabel').innerHTML = `
        <small class="text-muted">作者: ${data.username || ''}</small>
        <small class="text-muted ms-3">发布于: ${formatDate(data.created_at)}</small>
    `;
    
    // 根据内容类型生成不同的显示
    let contentHtml = '';
    
    if (data.type === 'text') {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || '文本内容')}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <p>${escapeHtml(data.content)}</p>
                </div>
            </div>
        `;
    } else if (data.type === 'image') {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || '图片内容')}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body text-center mb-3">
                    <img src="${data.file_path}" class="img-fluid rounded" style="max-height: 400px;" alt="上传的图片">
                </div>
                ${data.extracted_text ? `
                <div class="extracted-text p-3 bg-light rounded mb-3">
                    <h5>提取的文本:</h5>
                    <p>${escapeHtml(data.extracted_text)}</p>
                </div>
                ` : ''}
            </div>
        `;
    } else if (data.type === 'url') {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || data.url)}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <div class="url-content p-3 bg-light rounded">
                        <h5>页面内容:</h5>
                        <p>${escapeHtml(data.content)}</p>
                    </div>
                </div>
            </div>
        `;
    } else if (data.type === 'markdown') {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || 'Markdown 内容')}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <div class="markdown-body">${data.html_content || ''}</div>
                </div>
            </div>
        `;
    } else if (data.type === 'text_file') {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || '文本文件')}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <pre class="p-3 bg-light rounded" style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(data.content || '')}</pre>
                </div>
            </div>
        `;
    } else if (data.type === 'pdf') {
        // 检查内容是否包含目录
        let hasToc = data.content && data.content.includes('目录:');
        let pdfContent = hasToc ? data.content.split('\n\n').slice(1).join('\n\n') : (data.content || '无法提取文本');
        let tocContent = hasToc ? data.content.split('目录:')[1].split('\n\n')[0] : '';
        
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${data.title || 'PDF文档'}</h3>
                    <p class="text-muted">${data.page_count || 0} 页</p>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <div class="pdf-preview mb-3">
                        <div class="ratio ratio-16x9">
                            <iframe src="/api/preview/${data.id}" class="rounded border" allowfullscreen id="pdfViewer"></iframe>
                        </div>
                    </div>
                    <div class="pdf-actions mb-3">
                        <div class="row">
                            <div class="col-md-6 mb-2 mb-md-0">
                                <button class="btn btn-sm btn-outline-primary" id="togglePdfText">
                                    <i class="bi bi-text-paragraph me-1"></i>显示/隐藏提取的文本
                                </button>
                            </div>
                            <div class="col-md-6">
                                <div class="input-group">
                                    <input type="text" class="form-control form-control-sm" id="pdfSearchInput" 
                                           placeholder="在PDF中搜索..." aria-label="在PDF中搜索">
                                    <button class="btn btn-sm btn-outline-secondary" type="button" id="pdfSearchBtn">
                                        <i class="bi bi-search"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="pdf-search-results mb-3" id="pdfSearchResults" style="display: none;">
                        <div class="card">
                            <div class="card-header bg-light d-flex justify-content-between align-items-center">
                                <h6 class="mb-0">搜索结果</h6>
                                <button type="button" class="btn-close" id="closeSearchResults" aria-label="Close"></button>
                            </div>
                            <div class="card-body" id="searchResultsList">
                                <div class="text-center text-muted">请输入搜索词</div>
                            </div>
                        </div>
                    </div>
                    <div class="extracted-text p-3 bg-light rounded" id="pdfExtractedText" style="display: none;">
                        <h5>提取的文本:</h5>
                        ${hasToc ? `
                        <div class="pdf-toc mb-3 border-bottom pb-3">
                            <h6><i class="bi bi-list-ul me-1"></i>文档目录</h6>
                            <pre class="toc-content" style="white-space: pre-wrap; word-break: break-word;">${escapeHtml(tocContent)}</pre>
                        </div>
                        ` : ''}
                        <pre id="pdfContentText" style="white-space: pre-wrap; word-break: break-word; max-height: 500px; overflow-y: auto;">${escapeHtml(pdfContent)}</pre>
                    </div>
                </div>
            </div>
        `;
        
        // 添加事件处理
        setTimeout(() => {
            // 切换文本显示
            const toggleBtn = document.getElementById('togglePdfText');
            const textDiv = document.getElementById('pdfExtractedText');
            if (toggleBtn && textDiv) {
                toggleBtn.addEventListener('click', () => {
                    if (textDiv.style.display === 'none') {
                        textDiv.style.display = 'block';
                        toggleBtn.innerHTML = '<i class="bi bi-text-paragraph me-1"></i>隐藏提取的文本';
                    } else {
                        textDiv.style.display = 'none';
                        toggleBtn.innerHTML = '<i class="bi bi-text-paragraph me-1"></i>显示提取的文本';
                    }
                });
            }
            
            // PDF搜索功能
            const searchInput = document.getElementById('pdfSearchInput');
            const searchBtn = document.getElementById('pdfSearchBtn');
            const searchResults = document.getElementById('pdfSearchResults');
            const searchResultsList = document.getElementById('searchResultsList');
            const closeSearchResults = document.getElementById('closeSearchResults');
            const pdfContentText = document.getElementById('pdfContentText');
            
            if (searchBtn && searchInput && searchResults && searchResultsList && closeSearchResults) {
                // 搜索函数
                const performSearch = () => {
                    const searchTerm = searchInput.value.trim();
                    if (!searchTerm) {
                        searchResultsList.innerHTML = '<div class="text-center text-muted">请输入搜索词</div>';
                        return;
                    }
                    
                    // 显示搜索结果区域并显示加载状态
                    searchResults.style.display = 'block';
                    searchResultsList.innerHTML = '<div class="text-center"><div class="spinner-border spinner-border-sm text-primary" role="status"></div> <span>正在搜索...</span></div>';
                    
                    // 使用API在PDF中搜索
                    fetch(`/api/pdf/search/${data.id}?q=${encodeURIComponent(searchTerm)}`)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('搜索请求失败');
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.total > 0) {
                                let resultsHtml = `<p>找到 ${data.total} 个匹配项:</p><div class="list-group">`;
                                data.results.forEach((result, i) => {
                                    // 高亮搜索词
                                    let context = result.context;
                                    const searchTermRegex = new RegExp(searchTerm, 'gi');
                                    context = context.replace(searchTermRegex, match => `<mark>${match}</mark>`);
                                    
                                    resultsHtml += `
                                        <a href="#" class="list-group-item list-group-item-action search-result-item" 
                                           data-page="${result.page}" data-rect="${JSON.stringify(result.rect)}">
                                            <div class="d-flex justify-content-between">
                                                <span class="badge bg-secondary">${i + 1}</span>
                                                <span class="badge bg-primary">第 ${result.page} 页</span>
                                            </div>
                                            <p class="mb-1">...${context}...</p>
                                        </a>
                                    `;
                                });
                                resultsHtml += '</div>';
                                searchResultsList.innerHTML = resultsHtml;
                                
                                // 添加点击事件
                                document.querySelectorAll('.search-result-item').forEach(item => {
                                    item.addEventListener('click', (e) => {
                                        e.preventDefault();
                                        const page = parseInt(item.getAttribute('data-page'));
                                        // rect变量目前未使用，但保留以备将来扩展
                                        const rect = JSON.parse(item.getAttribute('data-rect'));
                                        
                                        // 在PDF中高亮显示匹配项
                                        const pdfViewer = document.getElementById('pdfViewer');
                                        if (pdfViewer) {
                                            // 构建带有页码和高亮参数的URL（目前未使用，但保留以备将来扩展）
                                            const highlightUrl = `/api/preview/${data.id}?page=${page - 1}&highlight=true`;
                                            
                                            // 如果支持PDF.js，可以使用更高级的高亮功能
                                            // 这里我们简单地跳转到对应页面
                                            const currentSrc = pdfViewer.src;
                                            const baseUrl = currentSrc.split('#')[0];
                                            pdfViewer.src = `${baseUrl}#page=${page}`;
                                            
                                            // 同时在提取的文本中显示
                                            textDiv.style.display = 'block';
                                            toggleBtn.innerHTML = '<i class="bi bi-text-paragraph me-1"></i>隐藏提取的文本';
                                            
                                            // 在提取的文本中高亮显示
                                            const searchTermRegex = new RegExp(searchTerm, 'gi');
                                            const baseText = escapeHtml(pdfContent);
                                            const highlightedContent = baseText.replace(searchTermRegex, m => `<mark class="search-highlight">${escapeHtml(m)}</mark>`);
                                            pdfContentText.innerHTML = highlightedContent;
                                            
                                            // 尝试滚动到第一个高亮位置
                                            setTimeout(() => {
                                                const firstHighlight = pdfContentText.querySelector('.search-highlight');
                                                if (firstHighlight) {
                                                    firstHighlight.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                                }
                                            }, 100);
                                        }
                                    });
                                });
                            } else {
                                searchResultsList.innerHTML = '<div class="text-center text-muted">未找到匹配项</div>';
                            }
                        })
                        .catch(error => {
                            console.error('搜索错误:', error);
                            searchResultsList.innerHTML = `<div class="alert alert-danger">搜索失败: ${error.message}</div>`;
                        });
                };
                
                // 绑定搜索按钮点击事件
                searchBtn.addEventListener('click', performSearch);
                
                // 绑定回车键搜索
                searchInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        performSearch();
                    }
                });
                
                // 关闭搜索结果
                closeSearchResults.addEventListener('click', () => {
                    searchResults.style.display = 'none';
                    // 恢复原始文本显示
                    if (pdfContentText) {
                        pdfContentText.innerHTML = pdfContent;
                    }
                });
            }
        }, 100);
    } else {
        contentHtml = `
            <div class="content-detail">
                <div class="content-header mb-4">
                    <h3>${escapeHtml(data.title || getContentTypeLabel(data.type))}</h3>
                </div>
                ${generateKeywordsSection(data.keywords, data)}
                <div class="content-body">
                    <p>${escapeHtml(data.content || data.extracted_text || '')}</p>
                </div>
            </div>
        `;
    }
    
    container.innerHTML = contentHtml;

    // 在头部插入下载和评论按钮
    try { setupContentActions(container, data); } catch (e) { console.warn('setup ContentActions failed', e); }

    // 批注功能会通过 annotations.js 中的事件监听自动初始化
    // 设置当前内容ID和用户信息供 annotations.js 使用
    window.currentContentId = data.id;
    window.currentUser = currentUser;


    if (data && data.id) {
        try {
            initInlineKeywordsInlineMode(data);
        } catch (e) {
            console.warn('init keywords inline failed', e);
        }
    }
}





// 生成内容项HTML
function generateContentItemHtml(item) {
    let keywordsHtml = '';
    let typeIcon = '';
    let typeClass = '';
    
    // 设置类型图标和样式
    switch (item.type) {
        case 'text':
            typeIcon = '<i class="bi bi-file-text"></i>';
            typeClass = 'content-type-text';
            break;
        case 'image':
            typeIcon = '<i class="bi bi-image"></i>';
            typeClass = 'content-type-image';
            break;
        case 'url':
            typeIcon = '<i class="bi bi-link-45deg"></i>';
            typeClass = 'content-type-url';
            break;
        case 'markdown':
            typeIcon = '<i class="bi bi-markdown"></i>';
            typeClass = 'content-type-markdown';
            break;
        case 'text_file':
            typeIcon = '<i class="bi bi-file-earmark-text"></i>';
            typeClass = 'content-type-text-file';
            break;
        case 'pdf':
            typeIcon = '<i class="bi bi-file-earmark-pdf"></i>';
            typeClass = 'content-type-pdf';
            break;
        default:
            typeIcon = '<i class="bi bi-file-earmark"></i>';
            typeClass = 'content-type-generic';
            break;
    }
    
    if (item.keywords && item.keywords.length > 0) {
        keywordsHtml = item.keywords.map(keyword => 
            `<span class="badge bg-primary keyword-badge" onclick="searchByKeyword('${keyword}', 'mainSearchResultsList', 'mainSearchResults')">${keyword}</span>`
        ).join(' ');
    }
    
    // 根据内容类型生成不同的布局
    if (item.type === 'text') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            ${item.content ? escapeHtml(item.content.substring(0, 300)) + (item.content.length > 300 ? '...' : '') : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (item.type === 'image') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row align-items-center">
                    <div class="col-6">
                        <div class="d-flex justify-content-center align-items-center" style="min-height: 200px;">
                            <img src="${item.file_path}" class="img-fluid rounded" 
                                 style="max-height: 300px; max-width: 100%; object-fit: contain; cursor: pointer;" 
                                 alt="上传的图片" 
                                 onclick="showContentInModal('${item.id}')">
                        </div>
                    </div>
                    <div class="col-6">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <div class="d-flex align-items-center">
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                                <small class="text-muted ms-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp ms-2">${formatDate(item.created_at)}</span>
                            </div>
                            <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                <i class="bi bi-chat-dots"></i>
                            </button>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            ${item.extracted_text ? escapeHtml(item.extracted_text.substring(0, 300)) + (item.extracted_text.length > 300 ? '...' : '') : '无法提取文本'}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (item.type === 'url') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            <div class="content-title mb-2">
                                <a href="${item.url}" target="_blank" class="text-decoration-none fw-bold">
                                    ${item.title || item.url}
                                    <i class="bi bi-box-arrow-up-right ms-1"></i>
                                </a>
                            </div>
                            ${item.content ? escapeHtml(item.content.substring(0, 300)) + (item.content.length > 300 ? '...' : '') : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (item.type === 'markdown') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            ${item.content ? escapeHtml(item.content.substring(0, 300)) + (item.content.length > 300 ? '...' : '') : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (item.type === 'text_file') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            ${item.content ? escapeHtml(item.content.substring(0, 300)) + (item.content.length > 300 ? '...' : '') : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else if (item.type === 'pdf') {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                                ${item.page_count ? `<span class="badge bg-secondary ms-2">${item.page_count} 页</span>` : ''}
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            <div class="d-flex align-items-center mb-2">
                                <i class="bi bi-file-earmark-pdf text-danger me-2" style="font-size: 1.2rem;"></i>
                                <span>PDF文档 - 点击查看详情和搜索内容</span>
                            </div>
                            ${item.content ? escapeHtml(item.content.substring(0, 250)) + (item.content.length > 250 ? '...' : '') : '无法提取文本'}
                        </div>
                    </div>
                </div>
            </div>
        `;
    } else {
        return `
            <div id="content-${item.id}" class="content-item fade-in">
                <div class="row">
                    <div class="col-2">
                        <div class="content-type-icon ${typeClass}">
                            ${typeIcon}
                        </div>
                    </div>
                    <div class="col-10">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <strong>
                                <a href="javascript:void(0)" onclick="showContentInModal('${item.id}')" class="content-title-link">
                                    ${item.title || getContentTypeLabel(item.type)}
                                </a>
                            </strong>
                            <div class="d-flex align-items-center">
                                <small class="text-muted me-2">by <a href="javascript:void(0)" onclick="showUserProfile(${item.user_id})" class="user-link">${item.username}</a></small>
                                <span class="timestamp me-2">${formatDate(item.created_at)}</span>
                                <button class="btn btn-sm btn-outline-primary" onclick="showComments('${item.id}')">
                                    <i class="bi bi-chat-dots"></i>
                                </button>
                            </div>
                        </div>
                        <div class="keywords mb-3">${keywordsHtml || '<span class="text-muted">无关键词</span>'}</div>
                        <div class="content-preview" onclick="showContentInModal('${item.id}')" style="cursor: pointer;">
                            ${escapeHtml((item.content || item.extracted_text || '').substring(0, 300))}${(item.content || item.extracted_text || '').length > 300 ? '...' : ''}
                        </div>
                    </div>
                </div>
            </div>
        `;
    }
}



// 加载最近内容
function loadRecentContent() {
    showLoading('recentContentList');
    
    fetch('/api/content')
        .then(response => response.json())
        .then(data => {
            displayRecentContent(data);
        })
        .catch(error => {
            console.error('Error:', error);
            document.getElementById('recentContentList').innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-exclamation-triangle me-2"></i>
                    加载最近内容失败: ${error.message || '未知错误'}
                </div>
            `;
        });
}

// 显示最近内容
function displayRecentContent(data) {
    const container = document.getElementById('recentContentList');
    
    if (!data.content || data.content.length === 0) {
        container.innerHTML = `
            <div class="alert alert-info">
                <i class="bi bi-info-circle me-2"></i>
                暂无内容，${currentUser ? '<a href="#" onclick="showUploadPage()" class="alert-link">点击这里上传第一个内容</a>' : '请先登录后上传内容'}
            </div>
        `;
        return;
    }
    
    // 只显示最近5个
    const recentItems = data.content.slice(0, 5);
    
    let contentHtml = '';
    
    recentItems.forEach(item => {
        contentHtml += generateContentItemHtml(item);
    });
    
    if (data.content.length > 5) {
        contentHtml += `
            <div class="text-center mt-3">
                <button class="btn btn-outline-primary" onclick="loadAllContent()">
                    <i class="bi bi-three-dots me-2"></i>查看全部 ${data.content.length} 个内容
                </button>
            </div>
        `;
    }
    
    container.innerHTML = contentHtml;
}

 // 加载全部内容
async function loadAllContent() {
    try {
        const response = await fetch('/api/content');
        const data = await response.json();
        if (data.content && data.content.length > 0) {
            let contentHtml = '';
            data.content.forEach(item => {
                contentHtml += generateContentItemHtml(item);
            });
            document.getElementById('recentContentList').innerHTML = contentHtml;
        } else {
            const el = document.getElementById('recentContentList');
            if (el) el.innerHTML = '';
        }
        return data;
    } catch (error) {
        console.error('Error:', error);
        throw error;
    }
}



// 辅助函数 - 显示加载中
function showLoading(containerId) {
    document.getElementById(containerId).innerHTML = `
        <div class="text-center p-4">
            <div class="spinner-border text-primary mb-3" role="status">
                <span class="visually-hidden">加载中...</span>
            </div>
            <p class="mb-0">加载中，请稍候...</p>
        </div>
    `;
}



// ========== 下载相关辅助 ==========






function setupContentActions(container, data) {
    try {
        const detailEl = container.querySelector('.content-detail');
        if (!detailEl) return;

        // 查找内容头部区域
        const headerEl = detailEl.querySelector('.content-header');
        if (headerEl) {
            // 创建按钮容器，放在header之后
            let actionsEl = detailEl.querySelector('.content-actions');
            if (!actionsEl) {
                actionsEl = document.createElement('div');
                actionsEl.className = 'content-actions d-flex justify-content-end mb-3';
                headerEl.insertAdjacentElement('afterend', actionsEl);
            }

            // 添加删除按钮（只有内容所有者或管理员可见）- 放在最前面
            if (!actionsEl.querySelector('.btn-delete-content') && currentUser) {
                // 检查是否是内容所有者或管理员
                if (currentUser.user_id === data.user_id || currentUser.role === 'admin') {
                    const deleteBtn = document.createElement('button');
                    deleteBtn.type = 'button';
                    deleteBtn.className = 'btn btn-sm btn-outline-primary btn-delete-content me-2';
                    deleteBtn.style.color = '#dc3545';
                    deleteBtn.style.borderColor = '#dc3545';
                    deleteBtn.innerHTML = '<i class="bi bi-trash me-1"></i>删除';
                    deleteBtn.onclick = function() {
                        if (confirm('确定要删除这个内容吗？此操作不可恢复。')) {
                            deleteContent(data.id);
                        }
                    };
                    actionsEl.appendChild(deleteBtn);
                }
            }
            
            // 如果是URL类型，添加访问原网页按钮
            if (data.type === 'url' && data.url && !actionsEl.querySelector('.btn-visit-url')) {
                const urlBtn = document.createElement('a');
                urlBtn.href = data.url;
                urlBtn.target = '_blank';
                urlBtn.className = 'btn btn-sm btn-outline-primary btn-visit-url me-2';
                urlBtn.innerHTML = '<i class="bi bi-box-arrow-up-right me-1"></i>访问原网页';
                actionsEl.appendChild(urlBtn);
            }

            // 已存在则不重复添加（分别判断两个按钮）
            if (!actionsEl.querySelector('.btn-download-content')) {
                const a = document.createElement('a');
                a.href = `/api/download/${data && data.id ? data.id : ''}`;
                a.className = 'btn btn-sm btn-outline-primary btn-download-content me-2';
                a.innerHTML = '<i class="bi bi-download me-1"></i>下载';
                if (data && data.id) actionsEl.appendChild(a);
            }

            if (!actionsEl.querySelector('.btn-view-comments')) {
                const b = document.createElement('button');
                b.type = 'button';
                b.className = 'btn btn-sm btn-outline-primary btn-view-comments';
                b.innerHTML = '<i class="bi bi-chat-dots me-1"></i>查看评论';
                b.onclick = function() { if (data && data.id) showComments(data.id); };
                actionsEl.appendChild(b);
            }
        } else {
            // 如果找不到header区域，回退到原来的方式
            let actionsEl = detailEl.querySelector('.content-actions');
            if (!actionsEl) {
                const bodyEl = detailEl.querySelector('.content-body');
                actionsEl = document.createElement('div');
                actionsEl.className = 'content-actions d-flex justify-content-end mb-3';
                if (bodyEl && bodyEl.parentNode) {
                    bodyEl.parentNode.insertBefore(actionsEl, bodyEl);
                } else {
                    detailEl.insertAdjacentElement('afterbegin', actionsEl);
                }
            }

            // 添加删除按钮（只有内容所有者或管理员可见）- 放在最前面
            if (!actionsEl.querySelector('.btn-delete-content') && currentUser) {
                // 检查是否是内容所有者或管理员
                if (currentUser.user_id === data.user_id || currentUser.role === 'admin') {
                    const deleteBtn = document.createElement('button');
                    deleteBtn.type = 'button';
                    deleteBtn.className = 'btn btn-sm btn-outline-primary btn-delete-content me-2';
                    deleteBtn.style.color = '#dc3545';
                    deleteBtn.style.borderColor = '#dc3545';
                    deleteBtn.innerHTML = '<i class="bi bi-trash me-1"></i>删除';
                    deleteBtn.onclick = function() {
                        if (confirm('确定要删除这个内容吗？此操作不可恢复。')) {
                            deleteContent(data.id);
                        }
                    };
                    actionsEl.appendChild(deleteBtn);
                }
            }
            
            // 如果是URL类型，添加访问原网页按钮
            if (data.type === 'url' && data.url && !actionsEl.querySelector('.btn-visit-url')) {
                const urlBtn = document.createElement('a');
                urlBtn.href = data.url;
                urlBtn.target = '_blank';
                urlBtn.className = 'btn btn-sm btn-outline-primary btn-visit-url me-2';
                urlBtn.innerHTML = '<i class="bi bi-box-arrow-up-right me-1"></i>访问原网页';
                actionsEl.appendChild(urlBtn);
            }

            // 已存在则不重复添加（分别判断两个按钮）
            if (!actionsEl.querySelector('.btn-download-content')) {
                const a = document.createElement('a');
                a.href = `/api/download/${data && data.id ? data.id : ''}`;
                a.className = 'btn btn-sm btn-outline-primary btn-download-content me-2';
                a.innerHTML = '<i class="bi bi-download me-1"></i>下载';
                if (data && data.id) actionsEl.appendChild(a);
            }

            if (!actionsEl.querySelector('.btn-view-comments')) {
                const b = document.createElement('button');
                b.type = 'button';
                b.className = 'btn btn-sm btn-outline-primary btn-view-comments';
                b.innerHTML = '<i class="bi bi-chat-dots me-1"></i>查看评论';
                b.onclick = function() { if (data && data.id) showComments(data.id); };
                actionsEl.appendChild(b);
            }
        }
    } catch (e) {
        console.warn('attach download failed', e);
    }
}
// ========== 下载相关辅助 End ==========

// 删除内容
function deleteContent(contentId) {
    if (!contentId) return;
    
    fetch(`/api/content/${contentId}/delete`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 关闭模态框
            const contentModal = bootstrap.Modal.getInstance(document.getElementById('contentViewModal'));
            if (contentModal) {
                contentModal.hide();
            }
            
            // 显示成功消息
            alert('内容已成功删除');
            
            // 刷新内容列表
            if (document.getElementById('mainSearchResultsList').innerHTML) {
                // 如果在搜索结果页，重新执行搜索
                handleMainSearch();
            } else {
                // 否则刷新最近内容
                loadRecentContent();
            }
        } else {
            alert(data.error || '删除内容失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除内容失败，请重试');
    });
}